package com.ruoyi.quartz.task;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.business.service.ITOrderInfoService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.common.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class HdfOrderCheckTask {



    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;

    private Log logger = Log.get();



    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    @Scheduled(fixedRate  = 5000)
    public void checkOrder() throws Exception {
//        logger.info("乐刷订单查询..");
        Calendar c = Calendar.getInstance();
        TOrderInfo query = new TOrderInfo();
        query.setChannelType("alipay");
        query.setChannel("alipay_hdf_h5");
        query.setStatus(1);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoList(query);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        Date startTime = DateUtils.getStartOfDay(new Date());
        Date endTime = DateUtils.getEndOfDay(new Date());
        String startTimeStr = sdf.format(startTime);
        String endTimeStr = sdf.format(endTime);
        for(TOrderInfo orderInfo:orderInfos){
            if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                continue;
            }
           TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
            String url = "https://api.haoduo.fun/finance/trans/getTransList";
            String cookieStr = userRecipientInfo.getCookie();
            JSONObject cookieObj = JSONObject.parseObject(cookieStr);
            String token =  cookieObj.getString("token");

            HashMap queryObj = new HashMap();

            queryObj.put("page","1");
            queryObj.put("startDate","");
            queryObj.put("page_size","30");
            queryObj.put("endDate","");
            String sign= MD5Util.stringMD5(SignUtil.formatUrlMap(queryObj,false)).toUpperCase();
            queryObj.put("sign",sign);
            HashMap<String, String> headerMap = new HashMap();
            headerMap.put("auth_token",token);
//            logger.info("订单查询请求："+SignUtil.formatUrlMap(queryObj,false));
            HttpResponse httpResponse = HttpUtils.httpFormPost(url, headerMap, "", queryObj, "好多分订单查询", "");
            JSONObject resultObj = JSONObject.parseObject(httpResponse.getDocument().body().text());
//            logger.info("好多分订单查询.."+resultObj);
            int resultCode = resultObj.getInteger("code");
            if(resultCode==200){
                JSONArray recordList = resultObj.getJSONObject("data").getJSONArray("list");
                for (int i=0;i<recordList.size();i++){
                    JSONObject recordObj = recordList.getJSONObject(i);
                    if(recordObj.getString("channel").equals("支付宝") && recordObj.getString("pay_state").equals("1") ){
                        //&& Float.valueOf(MoneyUtil.fenToYuan(orderInfo.getMoney() + "")).equals(recordObj.getFloatValue("order_amount"))
                        if(recordObj.getString("order_no").equals(orderInfo.getPay3rdOrderNo())){//成功订单
                            logger.info("好多分订单查询.."+recordObj);
                            MsgPayResult msgPayResult = new MsgPayResult();
                            msgPayResult.setChannel(orderInfo.getChannel());
                            msgPayResult.setTradeNo(orderInfo.getId().toString());
                            msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                            msgPayResult.setOrderId(recordObj.getString("order_no"));
                            msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
                            msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                            msgPayResult.setBillTime(recordObj.getString("pay_time"));

                            msgPayResult.setChannelPayMsgResult(JSONObject.toJSONString(recordObj));
                            chargeService.updateOrderPayResult(false,orderInfo.getId(),msgPayResult,false);
                            chargeService.notifyUserPaySucc(orderInfo.getId());

                            logger.info("好多分订单回调..订单号："+orderInfo.getId()+" 金额："+orderInfo.getMoney());
                        }
                    }
                }
            }else{
                logger.info("好多分订单查询.." + resultObj);
                String accountJson = userRecipientInfo.getAccountJson();
                JSONObject accountObj = JSONObject.parseObject(accountJson);
                cookieObj = new JSONObject();
                //https://www.shouyinbei.net/api/userInfo/13950341396/Ldw834391
                url = "https://api.haoduo.fun/merchant/login/loginByPwd";
                HashMap dataMap = new HashMap<>();
                String passport = userRecipientInfo.getChannelAccount().split("_")[0];
                dataMap.put("account", passport);
                dataMap.put("password", accountObj.getString("password"));
                String sing = MD5Util.stringMD5(SignUtil.formatUrlMap(dataMap, false)).toUpperCase();
                dataMap.put("sing", sing);
                 httpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "好多分登录请求", "");
                logger.info("好多分登录返回：" + httpResponse.getDocument().body().text());
                JSONObject loginResObj = JSONObject.parseObject(httpResponse.getDocument().body().text());
                if (loginResObj.getIntValue("code") == 200) {
                    JSONObject tokenData = loginResObj.getJSONObject("data");
                    token = tokenData.getString("auth_token");
                    TRecipientInfo  queryRecipientInfo = new TRecipientInfo();
                    queryRecipientInfo.setChannelAccount(passport);
                    queryRecipientInfo.setChannel("alipay_hdf_h5");
                    List<TRecipientInfo> userRecipientInfos = userRecipientService.selectTRecipientInfoList(queryRecipientInfo);
                    //获取所有商户
                    url = "https://api.haoduo.fun/v1/cashier/cashier/cashiers";
                    headerMap = new HashMap<>();
                    headerMap.put("auth_token", token);
                    headerMap.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 15_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Html5Plus/1.0 (Immersed/20) uni-app");
                    httpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "好多分登录请求", "");
                    JSONObject bussResObj = JSONObject.parseObject(httpResponse.getDocument().body().text());
                    logger.info("好多分店员列表：" + httpResponse.getDocument().body().text());

                    if (bussResObj.getIntValue("code") == 200) {
                        JSONArray merList = bussResObj.getJSONArray("data");
                        for (int i = 0; i < merList.size(); i++) {
                            JSONObject merObj = merList.getJSONObject(i);
                            cookieObj.put("roleId", merObj.getString("role_no"));
                            url = "https://api.haoduo.fun/merchant/login/loginByPwd";
                            dataMap = new HashMap<>();
                            dataMap.put("account", passport);
                            dataMap.put("password", accountObj.getString("password"));
                            dataMap.put("cashier", merObj.getString("role_no"));
                            sing = MD5Util.stringMD5(SignUtil.formatUrlMap(dataMap, false)).toUpperCase();
                            dataMap.put("sing", sing);
                            httpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "好多分登录请求", "");
                            logger.info("好多分店员" + merObj.getString("role_no") + "登录返回：" + httpResponse.getDocument().body().text());


                            bussResObj = JSONObject.parseObject(httpResponse.getDocument().body().text());
                            if (bussResObj.getIntValue("code") != 200) {
                                continue;
                            }
                            tokenData = bussResObj.getJSONObject("data");
                            token = tokenData.getString("auth_token");
                            cookieObj.put("token", token);
                            headerMap.put("auth_token", token);
                            //获取码牌
                            url = "https://api.haoduo.fun/pay/pay/payUrl";
                            httpResponse = HttpUtils.httpFormPost(url, headerMap, "", dataMap, "好多分登录请求", "");
                            bussResObj = JSONObject.parseObject(httpResponse.getDocument().body().text());
                            logger.info("好多分店员" + merObj.getString("role_no") + "获取返回：" + httpResponse.getDocument().body().text());
                            if (bussResObj.getIntValue("code") != 200) {
                                continue;
                            }
                            String qrCodeId = HttpUtils.getParamByUrl(bussResObj.getJSONObject("data").getString("url"), "qrCodeId");
                            cookieObj.put("qrCodeId", qrCodeId);

                            queryRecipientInfo = new TRecipientInfo();
                            queryRecipientInfo.setChannelAccount(passport + "_" + merObj.getString("role_no"));
                            queryRecipientInfo.setChannel("alipay_hdf_h5");
                            List<TRecipientInfo> userRecipientInfoList = userRecipientService.selectTRecipientInfoList(queryRecipientInfo);
                            if (userRecipientInfoList.size() == 0) {
                                if (i == 0) {
                                    userRecipientInfo.setChannelAccount(passport + "_" + merObj.getString("role_no"));
                                    userRecipientInfo.setOnline(1);
                                    userRecipientInfo.setCookie(cookieObj.toJSONString());
                                    userRecipientService.updateTRecipientInfo(userRecipientInfo);
                                } else {
                                    TRecipientInfo newRecipientInfo = new TRecipientInfo();
                                    BeanUtils.copyProperties(userRecipientInfo, newRecipientInfo);
                                    newRecipientInfo.setId(null);
                                    newRecipientInfo.setChannelAccount(passport + "_" + merObj.getString("role_no"));
                                    newRecipientInfo.setOnline(1);
                                    newRecipientInfo.setCookie(cookieObj.toJSONString());
                                    userRecipientService.insertTRecipientInfo(newRecipientInfo);
                                }
                            } else {
                                TRecipientInfo userRecipientInfo1 = userRecipientInfoList.get(0);
                                userRecipientInfo1.setOnline(1);
                                userRecipientInfo1.setCookie(cookieObj.toJSONString());
                                userRecipientService.updateTRecipientInfo(userRecipientInfo1);
                            }
                            queryRecipientInfo = new TRecipientInfo();
                            queryRecipientInfo.setChannelAccount(passport + "_" + merObj.getString("role_no"));
                            queryRecipientInfo.setChannel("alipay_hdf_h5");
                            userRecipientInfoList = userRecipientService.selectTRecipientInfoList(queryRecipientInfo);
                            logger.info("alipay_hdf_h5通道账号挂码个数："+userRecipientInfoList.size());
//                            queryRecipientInfo = new RecipientInfo();
//                            queryRecipientInfo.setChannelAccount(passport + "_" + merObj.getString("role_no"));
//                            queryRecipientInfo.setChannel("wechat_hdf_h5");
//                            List<RecipientInfo> wxuserRecipientInfoList = userRecipientService.getRecipientInfoListByAccount(queryRecipientInfo);
//                            logger.info("wechat_hdf_h5通道账号挂码个数："+wxuserRecipientInfoList.size());
//                            if(userRecipientInfoList.size()!=wxuserRecipientInfoList.size()){
//                                logger.info("未新增微信通道时，拷贝支付宝通道的挂号");
//                                for(RecipientInfo userRecipientInfo1:userRecipientInfoList){
//                                    queryRecipientInfo = new RecipientInfo();
//                                    queryRecipientInfo.setChannelAccount(userRecipientInfo1.getChannelAccount());
//                                    queryRecipientInfo.setChannel("wechat_hdf_h5");
//                                    List<RecipientInfo> userRecipientInfoList_1 = userRecipientService.getRecipientInfoListByAccount(queryRecipientInfo);
//                                    if(userRecipientInfoList_1.size()==0){
//                                        RecipientInfo tmp = new RecipientInfo();
//                                        BeanUtils.copyProperties(userRecipientInfo1, tmp);
//                                        tmp.setId(null);
//                                        tmp.setChannelType("wechat");
//                                        tmp.setChannel("wechat_hdf_h5");
//                                        userRecipientService.save(tmp);
//                                    }
//                                }
//                            }else{
//                                RecipientInfo userRecipientInfo1 = wxuserRecipientInfoList.get(0);
//                                userRecipientInfo1.setOnline(1);
//                                userRecipientInfo1.setCookie(cookieObj.toJSONString());
//                                userRecipientService.updateById(userRecipientInfo1);
//                            }

                        }

                    }
                }
            }
        }
    }

    private String timeStamp2Date(String str_num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }


}
